import json
import hou
import os
from PySide2 import QtWidgets, QtCore

class SettingsWindow(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Settings")
        self.setGeometry(200, 200, 400, 200)

        # 主布局
        self.layout = QtWidgets.QVBoxLayout(self)

        # 服务商选择
        self.provider_label = QtWidgets.QLabel("Select Provider:")
        self.provider_combo = QtWidgets.QComboBox()
        self.provider_combo.addItems(["DeepSeek", "OpenAI", "Siliconflow", "Custum"])
        self.layout.addWidget(self.provider_label)
        self.layout.addWidget(self.provider_combo)

        # API URL 输入
        self.api_url_label = QtWidgets.QLabel("API URL:")
        self.api_url_label.setVisible(False)
        self.api_url_input = QtWidgets.QLineEdit()
        self.api_url_input.setVisible(False)  # 默认隐藏
        self.layout.addWidget(self.api_url_label)
        self.layout.addWidget(self.api_url_input)

        # API Key 输入
        self.api_key_label = QtWidgets.QLabel("API Key:")
        self.api_key_input = QtWidgets.QLineEdit()
        self.layout.addWidget(self.api_key_label)
        self.layout.addWidget(self.api_key_input)

        # 保存按钮
        self.save_button = QtWidgets.QPushButton("Save")
        self.layout.addWidget(self.save_button)


        # 连接信号
        self.provider_combo.currentTextChanged.connect(self.on_provider_changed)
        self.save_button.clicked.connect(self.save_settings)

        # 加载配置
        self.load_config()

    def get_default_config(self):
        """返回默认的配置数据"""
        return [
            {"id": 0, "name": "DeepSeek", "api_url": "https://api.deepseek.com/v1", "key": ""},
            {"id": 1, "name": "OpenAI", "api_url": "https://api.openai.com/v1", "key": ""},
            {"id": 2, "name": "Siliconflow", "api_url": "https://api.siliconflow.com/v1", "key": ""},
            {"id": 3, "name": "Custum", "api_url": "", "key": ""},
            {"select": 0}
        ]

    def load_config(self):
        """加载配置文件"""
        current_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(current_dir, 'config.json')
        print(file_path)

        if os.path.exists(file_path):
            try:
                with open(file_path, "r") as config_file:
                    self.config_data = json.load(config_file)
            except json.JSONDecodeError:
                self.config_data = self.get_default_config()
        else:
            self.config_data = self.get_default_config()

        # 加载选中的服务商
        select_item = next((item for item in self.config_data if "select" in item), None)
        if select_item:
            selected_id = select_item["select"]
            provider_item = next((item for item in self.config_data if item.get("id") == selected_id), None)
            if provider_item:
                selected_provider = provider_item["name"]
                self.provider_combo.setCurrentText(selected_provider)
                # 加载 API Key 和 API URL
                self.api_key_input.setText(provider_item.get("key", ""))
                if selected_provider == "Custum":
                    self.api_url_input.setText(provider_item.get("api_url", ""))
                    self.api_url_input.setVisible(True)
                    self.api_url_label.setVisible(True)
            else:
                self.provider_combo.setCurrentText("DeepSeek")  # 默认选择第一个服务商
        else:
            self.provider_combo.setCurrentText("DeepSeek")  # 默认选择第一个服务商

    def on_provider_changed(self, provider):
        """当服务商选择变化时，显示或隐藏 API URL 输入框"""
        if provider == "Custum":
            self.api_url_input.setVisible(True)
            self.api_url_label.setVisible(True)
        else:
            self.api_url_input.setVisible(False)
            self.api_url_label.setVisible(False)

        # 更新选中的服务商
        provider_data = next((item for item in self.config_data if item["name"] == provider), None)
        if provider_data:
            self.api_key_input.setText(provider_data.get("key", ""))
            if provider == "Custum":
                self.api_url_input.setText(provider_data.get("api_url", ""))

    def show_message(self, message, severity=QtWidgets.QMessageBox.Information):
        """使用 PySide2 显示消息弹窗"""
        msg_box = QtWidgets.QMessageBox(self)  # 父窗口为当前窗口
        msg_box.setText(message)
        msg_box.setIcon(severity)
        msg_box.setWindowTitle("Message")
        msg_box.exec_()

    def save_settings(self):
        """保存配置到 config 文件"""
        api_provider = self.provider_combo.currentText()
        api_key = self.api_key_input.text().strip()

        if not api_key:
            self.show_message("API Key cannot be empty.", severity=QtWidgets.QMessageBox.Warning)
            return

        # 更新服务商的 Key 和 API URL
        provider_data = next((item for item in self.config_data if item["name"] == api_provider), None)
        if provider_data:
            provider_data["key"] = api_key
            if api_provider == "Custum":
                api_url = self.api_url_input.text().strip()
                if not api_url:
                    self.show_message("API URL cannot be empty for custom provider.", severity=QtWidgets.QMessageBox.Warning)
                    return
                provider_data["api_url"] = api_url

        # 更新选中的服务商
        provider_data = next((item for item in self.config_data if item["name"] == api_provider), None)
        if provider_data:
            selected_id = provider_data["id"]
            select_item = next((item for item in self.config_data if "select" in item), None)
            if select_item:
                select_item["select"] = selected_id

        # 保存设置到 config 文件
        current_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(current_dir, 'config.json')
        try:
            with open(file_path, "w") as config_file:
                json.dump(self.config_data, config_file, indent=4)
            self.show_message("Settings saved successfully.")
        except Exception as e:
            self.show_message(f"Failed to save settings: {str(e)}", severity=QtWidgets.QMessageBox.Critical)

        # 关闭设置窗口
        self.close()


def show_window():
    """显示设置窗口"""
    # 获取 Houdini 的主窗口
    main_window = hou.qt.mainWindow()

    # 创建自定义窗口，并将其附加到 Houdini 的主窗口
    window = SettingsWindow()
    window.setParent(main_window, QtCore.Qt.Window)  # 将窗口附加到 Houdini 的主窗口
    window.setWindowModality(QtCore.Qt.ApplicationModal) 
    window.show()  # 显示窗口
